package com.examinantsdk.base

import android.os.Build
import android.util.Log
import com.blankj.utilcode.util.StringUtils
import com.examinantsdk.getAndroidId
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

/**
 * Create by liuwei on 2021/11/11.
 */
class HeaderInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        var url = request.url
        val builder: Request.Builder = request.newBuilder()
        var token = ""
        if (!StringUtils.isEmpty(MyApplication.getToken())) {
            token = "Bearer " + MyApplication.getToken()
        }
        val headers = request.headers(
            Constants.Urls.HEADER_MEMBER.split(":".toRegex())
                .dropLastWhile { it.isEmpty() }.toTypedArray()[0]
        )
        if (headers.isNotEmpty()) {
            if (Constants.Urls.HEADER_MEMBER.split(":".toRegex())
                    .dropLastWhile { it.isEmpty() }.toTypedArray()[1] == headers[0]
            ) {
                builder.removeHeader(
                    Constants.Urls.HEADER_MEMBER.split(":".toRegex())
                        .dropLastWhile { it.isEmpty() }.toTypedArray()[0]
                )
                val baseURL = Constants.Urls.MEMBER_BASE_URL.toHttpUrlOrNull()
                url = url.newBuilder()
                    .scheme(baseURL!!.scheme)
                    .host(baseURL.host)
                    .port(baseURL.port)
                    .build()
            }
        }
        val requestBuilder: Request.Builder = request.newBuilder()
            .addHeader("Authorization", token)
            .addHeader("Accept", "application/json")
            .addHeader("Response-Format", "object")
            .addHeader("DeviceType", "Android")
            .addHeader("DeviceName", Build.MODEL)
            .addHeader("DeviceBrand", Build.MANUFACTURER)
            .addHeader("DeviceID", getAndroidId(MyApplication.context))
            .addHeader("SystemVersion", Build.VERSION.RELEASE)
            .addHeader("AppVersion", MyApplication.getVersionName())
            .addHeader("RequestPlatform", "KSY-CY-SDK")
            .method(request.method, request.body)
        val updateRequest: Request = requestBuilder.url(url).build()
        Log.d("Api=>", "headers | " + updateRequest.headers)
        return chain.proceed(updateRequest)
    }
}